package com.ruoyi.project.park.controller;

import java.math.BigDecimal;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import com.ruoyi.common.utils.IdUtils;
import com.ruoyi.project.park.domain.*;
import com.ruoyi.project.park.service.*;
import javafx.print.Collation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 停车记录Controller
 *
 * @author ruoyi
 * @date 2024-04-08
 */
@RestController
@RequestMapping("/park/record")
public class BizEntryRecordController extends BaseController {
    @Autowired
    private IBizEntryRecordService bizEntryRecordService;
    @Autowired
    private IBizParkingCardService bizParkingCardService;

    /**
     * 查询停车记录列表
     */
    @PreAuthorize("@ss.hasPermi('park:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizEntryRecord bizEntryRecord) {
        //判断当前登录用户是否为管理员
        if (!getLoginUser().getUser().getUserId().equals(1L)) {
            //不是管理员
            //去停车卡表查询出当前用户对应的车牌号
            BizParkingCard bizParkingCard = new BizParkingCard();

            bizParkingCard.setCardNumber(getUsername());
            BizParkingCard card = bizParkingCardService.selectBizParkingCardList(bizParkingCard).get(0);
            //bizEntryRecord.setVehicleLicensePlate(card.getVehicleLicensePlate());
            bizEntryRecord.setCreateBy(getUsername());
            bizEntryRecord.setCreatBy(getUsername());
        }
        startPage();
        List<BizEntryRecord> list = bizEntryRecordService.selectBizEntryRecordList(bizEntryRecord);
        return getDataTable(list);
    }

    /**
     * 导出停车记录列表
     */
    @PreAuthorize("@ss.hasPermi('park:record:export')")
    @Log(title = "停车记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizEntryRecord bizEntryRecord) {
        List<BizEntryRecord> list = bizEntryRecordService.selectBizEntryRecordList(bizEntryRecord);
        ExcelUtil<BizEntryRecord> util = new ExcelUtil<BizEntryRecord>(BizEntryRecord.class);
        util.exportExcel(response, list, "停车记录数据");
    }

    /**
     * 获取停车记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('park:record:query')")
    @GetMapping(value = "/{entryRecordId}")
    public AjaxResult getInfo(@PathVariable("entryRecordId") String entryRecordId) {
        return AjaxResult.success(bizEntryRecordService.selectBizEntryRecordByEntryRecordId(entryRecordId));
    }


    @Autowired
    private IBizParkingService parkingService;
    @Autowired
    private IBizFeeStandardService bizFeeStandardService;

    @Autowired
    private IBizFeeRecordService feeRecordService;
    @Autowired
    private IBizParkingCardService cardService;

    /**
     * 新增停车记录
     */
    @PreAuthorize("@ss.hasPermi('park:record:add')")
    @Log(title = "停车记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizEntryRecord bizEntryRecord) {
        String userName = getLoginUser().getUser().getUserName();

        //判断当前登录用户是否为管理员
        String plate = null;
        if (!getLoginUser().getUser().getUserId().equals(1L)) {
            //不是管理员
            bizEntryRecord.setCreateBy(userName);
            bizEntryRecord.setCreatBy(userName);
            //去停车卡表查询出当前用户对应的车牌号
            BizParkingCard bizParkingCard = new BizParkingCard();
            //bizParkingCard.setCardNumber(getUsername());
            BizParkingCard card = bizParkingCardService.selectBizParkingCardList(bizParkingCard).get(0);
            plate = card.getVehicleLicensePlate();
        }

        //生成雪花id
        String nextIdStr = new Snowflake(1, 1).nextIdStr();
        bizEntryRecord.setEntryRecordId(nextIdStr);
        //entryType 1进站 2 出站
        /**
         * 1.进站的时候 需要判断有没有空闲车位 然后修改车位状态 还需要判断车牌号是否有会员卡
         * 2.出站的时候 需要判断是否有进站记录
         * 3.出站之后 产生费用 扣会员卡的余额
         *
         */
        String entryType = bizEntryRecord.getEntryType();
        //取到车牌号
        String vehicleLicensePlate = bizEntryRecord.getVehicleLicensePlate();
//        if (!vehicleLicensePlate.equals(plate)) {
//            return AjaxResult.error("车牌号与当前登录用户不匹配");
//        }

        //查询会员卡余额(根据车牌号)
        BizParkingCard parkingCard2 = new BizParkingCard();
        parkingCard2.setVehicleLicensePlate(vehicleLicensePlate);
        List<BizParkingCard> parkingCards2 = cardService.selectBizParkingCardList(parkingCard2);
        if (parkingCards2.size() == 0) {
            //没有会员卡
            //return AjaxResult.error("该车没有办理会员卡，无法停车");
            //临时停车
        }

        if (Objects.equals(entryType, "1")) {
            //根据车牌号去车位表查询，如果已经存在，则报错
            BizParking park = new BizParking();
            park.setVehicleLicensePlate(vehicleLicensePlate);
            List<BizParking> bizParkings = parkingService.selectBizParkingList(park);
            System.out.println("bizParkings");
            System.out.println(bizParkings);
            if (bizParkings.size() > 0) {
                return AjaxResult.error("该车已经停车，请勿重复停车");
            }

            //进站 查询出状态为空闲的
            BizParking bizParking = new BizParking();
            // vacancyStatus 1 空闲 2 已占用
            bizParking.setVacancyStatus("1");
            List<BizParking> parkingList = parkingService.selectBizParkingList(bizParking);
            if (parkingList.size() == 0) {
                //车位已满
                return AjaxResult.error("车位已满");
            }
            //打乱parkingList
            //打乱list
            Collections.shuffle(parkingList);
            //随机选一个车位
            //BizParking nowPark = parkingList.get(0);
            //修改为在空闲的车位里面找出前端传过来的
            //前端传参
            String parkingId = bizEntryRecord.getParkingId();
            //在parkingList中找出id等于parkingId的
            BizParking nowPark = parkingList.stream().filter( i-> i.getId().equals(parkingId)).findFirst().get();
            //修改状态
            nowPark.setVacancyStatus("2");
            nowPark.setVehicleLicensePlate(vehicleLicensePlate);
            nowPark.setParkingStartTime(new Date());
            parkingService.updateBizParking(nowPark);
        } else if (Objects.equals(entryType, "2")) {
            //出站
            //根据车牌号查询出最后一次进站记录
            BizEntryRecord lastEntryRecord = new BizEntryRecord();
            lastEntryRecord.setVehicleLicensePlate(vehicleLicensePlate);
            //lastEntryRecord.setEntryType("1");
            List<BizEntryRecord> lastEntryRecordList = bizEntryRecordService.selectBizEntryRecordList(lastEntryRecord);
            //判断最后一次是否为进站
            //lastEntryRecordList 排序 最新的排在最前面
            BizEntryRecord lastEntry;
            if (lastEntryRecordList.size() == 0) {
                //没有进站记录
                return AjaxResult.error("没有进站记录");
            } else {
                //按照时间排序，最新的排到最前面
                lastEntryRecordList.sort(Comparator.comparing(BizEntryRecord::getEntryTime));
                //倒序
                Collections.reverse(lastEntryRecordList);
                lastEntryRecordList.forEach(System.out::println);
                lastEntry = lastEntryRecordList.get(0);
                if (!lastEntry.getEntryType().equals("1")) {
                    return AjaxResult.error("没有进站记录");
                }

            }

            Date entryTime = lastEntry.getEntryTime();
            //计算费用
            String carType = lastEntry.getCarType();
            //去计费标准表查询收费记录
            BizFeeStandard bizFeeStandard = new BizFeeStandard();
            bizFeeStandard.setVehicleType(carType);
            List<BizFeeStandard> bizFeeStandards = bizFeeStandardService.selectBizFeeStandardList(bizFeeStandard);
            //结果应该为1个
            BizFeeStandard feeStandard = bizFeeStandards.get(0);
            Long initialFreeHours = feeStandard.getInitialFreeHours();
            //每小时费用
            BigDecimal hourlyRate = feeStandard.getHourlyRate();
            //固定费用
            BigDecimal feeAmount = feeStandard.getFeeAmount();
            //hutools 计算两个时间相差的分钟数\
            long between = DateUtil.between(entryTime, new Date(), DateUnit.MINUTE);
            BigDecimal allMoney = new BigDecimal(0);
            //转换为小时
            if (between <= initialFreeHours * 60) {
                //免费
                allMoney = BigDecimal.ZERO;
            } else {
                allMoney = feeAmount.add(new BigDecimal(between - initialFreeHours * 60).divide(new BigDecimal(60), 2, BigDecimal.ROUND_UP).multiply(hourlyRate));
            }
            //查询会员卡余额(根据车牌号)
            if (parkingCards2.size() != 0) {
                BizParkingCard parkingCard = new BizParkingCard();
                parkingCard.setVehicleLicensePlate(vehicleLicensePlate);
                List<BizParkingCard> parkingCards = cardService.selectBizParkingCardList(parkingCard);
                if (parkingCards.size() == 0) {
                    //没有会员卡
                    return AjaxResult.error("没有会员卡");
                } else {
                    //有会员卡
                    BizParkingCard parkingCard1 = parkingCards.get(0);
                    if (parkingCard1.getBalance().compareTo(allMoney) < 0) {
                        //余额不足
                        return AjaxResult.error("余额不足");
                    } else {
                        //释放车位(将车位的占用状态改为空闲)
                        BizParking bizParking = new BizParking();
                        // 1 空闲 2 已经占用
                        bizParking.setVacancyStatus("2");
                        bizParking.setVehicleLicensePlate(vehicleLicensePlate);
                        //去查询
                        List<BizParking> parkingList = parkingService.selectBizParkingList(bizParking);
                        //时间倒序
                        parkingList.sort(Comparator.comparing(BizParking::getCreateTime).reversed());
                        System.out.println("parkingList");
                        System.out.println(parkingList);

                        //应该只能查询出来一个
                        if (parkingList.size() <1) {
                            return AjaxResult.error("车位异常");
                        } else {
                            BizParking nowPark = parkingList.get(0);
                            System.out.println("nowPark");
                            System.out.println(nowPark);
                            BizParking bizParking1 = new BizParking();
                            bizParking1.setVacancyStatus("1");
                            bizParking1.setId(nowPark.getId());
                            //置空
                            bizParking1.setVehicleLicensePlate("  ");
                            System.out.println("bizParking1");
                            System.out.println(bizParking1);
                            parkingService.updateBizParking(bizParking1);
                        }

                        //余额足够
                        //扣余额
                        parkingCard1.setBalance(parkingCard1.getBalance().subtract(allMoney));
                        cardService.updateBizParkingCard(parkingCard1);
                        //增加收费记录
                        BizFeeRecord feeRecord = new BizFeeRecord();
                        feeRecord.setFeeRecordId(Long.valueOf(new Snowflake(1, 1).nextIdStr()));
                        feeRecord.setVehicleLicensePlate(vehicleLicensePlate);
                        feeRecord.setFeeAmount(allMoney);
                        //1临时停车 2停车卡
                        feeRecord.setPaymentType("2");
                        feeRecord.setEntryTime(lastEntry.getEntryTime());
                        feeRecord.setBillingTime(new Date());
                        feeRecord.setExitTime(new Date());
                        feeRecord.setCreatBy(getUsername());
                        feeRecord.setCreatBy(getUsername());
                        //入库
                        feeRecordService.insertBizFeeRecord(feeRecord);

                    }


                }
            } else {
                //临时停车
                //释放车位
                //释放车位(将车位的占用状态改为空闲)
                BizParking bizParking = new BizParking();
                // 1 空闲 2 已经占用
                bizParking.setVacancyStatus("2");
                bizParking.setVehicleLicensePlate(vehicleLicensePlate);
                //去查询
                List<BizParking> parkingList = parkingService.selectBizParkingList(bizParking);
                System.out.println("parkingList");
                System.out.println(parkingList);
                //时间倒序
                parkingList.sort(Comparator.comparing(BizParking::getCreateTime).reversed());

                //应该只能查询出来一个
                if (parkingList.size() <1) {
                    return AjaxResult.error("车位异常");
                } else {
                    BizParking nowPark = parkingList.get(0);
                    System.out.println("nowPark");
                    System.out.println(nowPark);
                    BizParking bizParking1 = new BizParking();
                    bizParking1.setVacancyStatus("1");
                    bizParking1.setId(nowPark.getId());
                    //置空
                    bizParking1.setVehicleLicensePlate("  ");
                    System.out.println("bizParking1");
                    System.out.println(bizParking1);
                    parkingService.updateBizParking(bizParking1);
                }

                //增加收费记录
                BizFeeRecord feeRecord = new BizFeeRecord();
                feeRecord.setFeeRecordId(Long.valueOf(new Snowflake(1, 1).nextIdStr()));
                feeRecord.setVehicleLicensePlate(vehicleLicensePlate);
                feeRecord.setFeeAmount(allMoney);
                //1临时停车 2停车卡
                feeRecord.setPaymentType("1");
                feeRecord.setEntryTime(lastEntry.getEntryTime());
                feeRecord.setBillingTime(new Date());
                feeRecord.setExitTime(new Date());
                feeRecord.setCreatBy(getUsername());
                feeRecord.setCreatBy(getUsername());
                //入库
                feeRecordService.insertBizFeeRecord(feeRecord);

            }
        }


        bizEntryRecord.setEntryTime(new Date());
        return toAjax(bizEntryRecordService.insertBizEntryRecord(bizEntryRecord));
    }

    /**
     * 修改停车记录
     */
    @PreAuthorize("@ss.hasPermi('park:record:edit')")
    @Log(title = "停车记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizEntryRecord bizEntryRecord) {
        return toAjax(bizEntryRecordService.updateBizEntryRecord(bizEntryRecord));
    }

    /**
     * 删除停车记录
     */
    @PreAuthorize("@ss.hasPermi('park:record:remove')")
    @Log(title = "停车记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{entryRecordIds}")
    public AjaxResult remove(@PathVariable String[] entryRecordIds) {
        return toAjax(bizEntryRecordService.deleteBizEntryRecordByEntryRecordIds(entryRecordIds));
    }
}
